
/*
*
* ssimg.js
* 上传图片
*
*
* */

;(function ($, window) {

    //上传
    var upload = function (file, key, callback) {

        var index = layer.load(2, { shade:0.2 });
        var url = '/bus/upload/upload_pic?key='+key;
        //构造表单
        var form = new FormData();
        form.append("file", file);

        //创建上传对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", url, true);
        xhr.onloadend = function (e) {
            layer.close(index);
            var obj = JSON.parse(e.currentTarget.responseText);
            callback(obj);
        };
        xhr.send(form);
    };

    //创建选择文件对象
    var select = function (accept, key, callback) {
        var fileObj = document.createElement("input");
        fileObj.setAttribute("type", "file");
        fileObj.setAttribute("accept", accept);
        fileObj.setAttribute("style", "display:none");
        $(fileObj).change(function () {
            var file = fileObj.files[0];
            upload(file, key, callback);
        });
        fileObj.click();
    };

    //初始化
    var init = function(option){

        //初始化界面
        var el = $(option.el);
        var html = '<div class="ssimg"><img src="" /><span class="delete"></span></div>';
        el.hide();
        el.after(html);
        el.parent().find('img').attr('src', el.val());

        if(option.width){
            el.parent().find('.ssimg').css('width', option.width);
        }
        if(option.height){
            el.parent().find('.ssimg').css('height', option.height);
        }

        //选择添加图片
        el.parent().on('click', '.ssimg', function () {
            select(option.accept, option.key, function (data) {
                el.val(data);
                console.log(data.file_url);
                el.parent().find('img').attr('src', data.file_url);
                if(typeof option.callback != 'undefined'){
                    option.callback(data);
                }
            });
        });

        //删除图片
        el.parent().on('click', '.delete', function () {
            el.val('');
            el.parent().find('img').attr('src', '');
            if(typeof option.delete != 'undefined'){
                option.delete();
            }
            return false;
        });
    }


    /*
    * 上传单张图片
    * el    绑定的控件
    * key   后台参数
    * accept    接受图片类型
    * callback  上传后回调
    * delete    删除后回调
    *
    * */
    window.ssimg = {
        init:init
    };

})($, window);


